/*
 * caso_write1.c
 *
 *  Created on: 08/11/2009
 *      Author: ivansalles
 *
 */

#include <fs.h>
#include <driver.h>
#include <pcb.h>

#include <stdlib.h>
#include <unistd.h>
#include <sys/msg.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>

PCB pcb;


int initDriverStub();


int main(){


	int retorno_read = 0;

		inode* i_node;

		/**
		 * Inicializando PCB
		 */
		pcb.pid = 123;
		pcb.user = 1;
		pcb.group = 1;
		pcb.current_dir = 0;

		/**
		 *	Inicializando os descritores
		 */

		//Inicializo o primeiro descritor
		pcb.descriptors[0].usado = 1;
		pcb.descriptors[0].mode = WRITE_MODE;
		pcb.descriptors[0].fpos = 0;
		pcb.descriptors[0].buffer_changed = 0;
		pcb.descriptors[0].buffer_block = -1;
		pcb.descriptors[0].buffer = malloc(BLOCK_SIZE);

		//Seto todos os demais descritores com zero em todos os campos
		memset(pcb.descriptors + 1, 0, 19*sizeof(FILE_SO));

		/**
		 * Inicializo uma entrada na TAA
		 */
		pcb.descriptors[0].ptr_fentry = (fentry*) malloc(sizeof(fentry));

		pcb.descriptors[0].ptr_fentry->fcount = 1;
		pcb.descriptors[0].ptr_fentry->inode_num = 2;
		pcb.descriptors[0].ptr_fentry->next = 0;

		i_node = &(pcb.descriptors[0].ptr_fentry->f_inode);

		i_node->tipo_arquivo = 'r';
		i_node->f_access_date = 0;
		i_node->f_change_date = 0;
		i_node->f_create_date = 0;
		i_node->f_owner = 1;
		i_node->f_group = 1;
		i_node->f_permissions = OWNER_WRITE_PERMISSION;
		i_node->f_size = 1029;

		memset(i_node->direct_blocks, 0, 10);

		i_node->direct_blocks[0] = 600;
		i_node->direct_blocks[1] = 601;

		i_node->single_indirection = 0;
		i_node->double_indirection = 0;
		i_node->triple_indirection = 0;

		initDriverStub();

		char buffer[4];

		buffer[0] = 0;
		buffer[1] = 1;
		buffer[2] = 2;
		buffer[3] = 3;

		int ret = write(0, buffer, 4, 1022);

		printf("Retorno: %d ERRNO: %d\n\n", ret, errno);



	return 0;
}

int carrega_bloco_no_buffer(int end_bloco, void* ptr_buffer){

	memset(ptr_buffer, 3, BLOCK_SIZE);

	return 0;
}
int atualizar_bloco(int end_bloco, void* ptr_buffer){
	return 0;
}

/**
 * Inicia em uma novo thread que simula o driver.
 */
int initDriverStub(){

	int rtn = fork();

	requisicao req;

	resposta resp;

	int req_id;

	int resp_id;

	int i = 0;

	if(rtn == 0){

		if(req_id = msgget(DRIVER_QUEUE_REQ, IPC_CREAT | 0666) == -1){
			printf("Erro ao criar fila de requisicao - %s\n", strerror(errno));
			return -1;
		}

		if(resp_id = msgget(DRIVER_QUEUE_RESP, IPC_CREAT | 0666) == -1){
			printf("Erro ao criar fila de resposta - %s\n", strerror(errno));
			return -1;
		}

		while(true){

			if(msgrcv(req_id, &req, sizeof(requisicao) - sizeof(long), 0, 0) == -1){
				printf("Erro ao receber mensagem - %s\n", strerror(errno));
			}

			resp.pid = req.pid = 0;

			printf("Escrevendo no bloco %d os dados: ", req.end_bloco);

			for(i = 0; i < BLOCK_SIZE; i++){
				printf("%d ", ((char*)req.buffer)[i]);
			}

			msgsnd(resp_id, &resp, sizeof(resposta) - sizeof(long), 0);
		}
	}

	return rtn;
}
